import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Md5 } from 'ts-md5/dist/md5';
import * as CryptoJS from 'crypto-js';
import { ConfigService } from './config.service';
import { Buffer } from 'buffer';
import * as $ from 'jquery';

@Injectable({
  providedIn: 'root'
})
export class ToolService {
  private platform: Platform;
  constructor(public platformV: Platform) {
    this.platform = platformV;
  }
  /**
   *两个json的数据合并
   *
   * @param {*} jsonbject1
   * @param {*} jsonbject2
   * @returns
   * @memberof ToolService
   */
  static concat(jsonbject1, jsonbject2) {
    var resultJsonObject = {};
    for (var attr in jsonbject1) {
      resultJsonObject[attr] = jsonbject1[attr];
    }
    for (var attr2 in jsonbject2) {
      resultJsonObject[attr2] = jsonbject2[attr2];
    }
    return resultJsonObject;
  }

  static setEncrypt(encrypt) {
    $("app-root").attr("encrypt", encrypt);
  }
  /**
   * md5加密
   */
  static Md5(str: any) {
    return Md5.hashStr(str).toString();
  }
  /**
   * AES加密
   * @param data 
   */
  static aesEncode(data: any, isForce?: boolean) {
    let encrypt = (!ToolService.isEmpty($("app-root").attr("encrypt")) && $("app-root").attr("encrypt") == '1') ? 1 : 0;
    if (encrypt == 1 || isForce) {
      let tempData = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(ConfigService.AES_KEY), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
        iv: '',
      }).toString();
      return new Buffer(tempData).toString('base64');
    } else {
      return data;
    }
  }

  /**
   * AES解密
   * @param data 
   */
  static aesDecode(data: any, isForce?: boolean) {
    let encrypt = (!ToolService.isEmpty($("app-root").attr("encrypt")) && $("app-root").attr("encrypt") == '1') ? 1 : 0;
    if (encrypt == 1 || isForce) {
      const decipher = CryptoJS.AES.decrypt((new Buffer(data, 'base64')).toString(), CryptoJS.enc.Utf8.parse(ConfigService.AES_KEY), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
        iv: '',
      });
      // 将解密对象转换成 UTF8 的字符串
      const resultDecipher = CryptoJS.enc.Utf8.stringify(decipher);
      // 返回解密结果
      return resultDecipher;
    } else {
      return data;
    }

  }

  static aesDecodeToJson(data: any, isForce?: boolean) {
    let res = this.aesDecode(data, isForce);
    if ((typeof res) != 'string') {
      res = JSON.stringify(res)
    }
    if (this.jsJson(res)) {
      return JSON.parse(res);
    } else {
      return {};
    }
  }

  /**
  * 判断字符串是否为空
  */
  static isEmpty(obj: any): boolean {
    if (typeof obj === "undefined" || obj === null || obj === "Null" || obj === "null" || obj === "" || JSON.stringify(obj) === '{}') {
      return true;
    } else {
      return false;
    }
  }

  /**
  * 获取运行的平台设备
  */
  getPlatform(): string {
    let dirviceType = "";
    let u = navigator.userAgent
    var ua = u.toLowerCase();
    if (ua.indexOf('micromessenger') != -1) {
      dirviceType = "weixin";
    }
    if (this.platform.is("android")) {
      dirviceType = "android";
    }
    if (this.platform.is("ios")) {
      dirviceType = "ios";
    }
    return dirviceType;
  }


  /**
 * 将obj的json转换为string的json
 * @param data 
 */
  static objJsonToStringJson(data): string {
    if (!this.isEmpty(data)) {
      if (typeof (data) == "string") {
        return data;
      } else {
        return JSON.stringify(data);
      }
    } else {
      return "{}";
    }
  }
  /**
   * 验证是否是手机号
   */
  static isMobilePhoneNumber(inputNumber: string): boolean {
    let myVerify = new RegExp("^[1][3,4,5,7,8][0-9]{9}$");
    if (myVerify.test(inputNumber)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 验证是否是纯数字
   */
  static isNumber(number: any): boolean {
    let myVerify = new RegExp("^[0-9]*$");
    if (myVerify.test(number)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 验证是否是邮箱
   */
  static isEmail(email: string): boolean {
    let myVerify = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
    if (myVerify.test(email)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 去除字符串中的空格
   * @param text 
   */
  static trim(text: any) {
    if (typeof (text) == "string") {
      return text.replace(/^\s*|\s*$/g, "");
    } else {
      return text;
    }
  }
  //b是当前app的版本号,a是服务端返回的版本号
  static versionfunegt(a, b) {
    var _a = toNum(a), _b = toNum(b);
    if (_a == _b) {
      console.log("版本号相同！版本号为：" + a);
      return false;
    } else if (_a > _b) {
      console.log("版本号" + a + "是新版本！");
      return true;
    } else {
      console.log("版本号" + b + "是新版本！");
      return false;
    }

    function toNum(a) {
      var a = a.toString();
      //也可以这样写 var c=a.split(/\./);
      var c = a.split('.');
      var num_place = ["", "0", "00", "000", "0000"], r = num_place.reverse();
      for (var i = 0; i < c.length; i++) {
        var len = c[i].length;
        c[i] = r[len] + c[i];
      }
      var res = c.join('');
      return res;
    }
  }

  /**
   * 对html的数据进行转码
   * @param text 一段html的数据
   */
  static htmlEncode(text: any) {
    return text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  }
  /**
   * 是否是身份证卡
   * 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
   * @param s  
   */
  static isIdCard(s) {
    return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(s);
  }
  /**
   * 是否是url
   * @param s 
   */
  static isUrl(s) {
    return /^http[s]?:\/\/.*/.test(s);
  }
  /**
   * 是否保留两位小数
   */
  static isDecimal = function (s) {
    return /^\d+$|^\d*\.\d+$/.test(s);
  }

  /**
   * ?判断是否是json对象
   * @param str 
   * @param pass_object 
   */
  static jsJson(str: any, pass_object?: boolean) {
    let that = this;
    if (pass_object && (Object.prototype.toString.call(str) === '[object Object]')) {
      return true;
    }
    if (!(Object.prototype.toString.call(str) === '[object String]')) {
      return false;
    }
    str = str.replace(/\s/g, '').replace(/\n|\r/, '');
    if (/^\{(.*?)\}$/.test(str)) {
      return /"(.*?)":(.*?)/g.test(str);
    }
    if (/^\[(.*?)\]$/.test(str)) {
      return str.replace(/^\[/, '')
        .replace(/\]$/, '')
        .replace(/},{/g, '}\n{')
        .split(/\n/)
        .map(function (s) {
          return that.jsJson(s);
        })
        .reduce(function (prev, curr) {
          return !!curr;
        });
    }
    return false;
  }

  static isStringJSON(str: any) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        //  console.log('error：'+str+'!!!'+e);
        return false;
      }
    }
    //  console.log('It is not a string!')
  }
  /**
   * 判断一个数组中是否存在某一个键值
   * @param ary 目标对象或数组
   * @param key 键值
   */
  static isExitKey(ary: any[], key) {
    if (ary.hasOwnProperty(key)) {
      return true;
    } else {
      return false;
    }
  }


  /**
   * 获取当前时间的年月日
   * @param seperator1 年月日的分割符号
   */
  static getNowFormatDate(seperator1: string = "-") {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    let resMonth = "";
    let resDate = "";
    if (month >= 1 && month <= 9) {
      resMonth = "0" + month;
    } else {
      resMonth = month + "";
    }
    if (strDate >= 0 && strDate <= 9) {
      resDate = "0" + strDate;
    } else {
      resDate = strDate + "";
    }
    let currentdate = year + seperator1 + resMonth + seperator1 + resDate;
    return currentdate;
  }

  static keepTwoDecimal(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
      return false;
    }
    result = Math.round(num * 100) / 100;
    return result.toFixed(2);
  }

  static keepThreeDecimal(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
      return false;
    }
    return result.toFixed(3);
  }

  static formateTime(seconds, isHideHour?: boolean) {
    if (seconds <= 0) {
      return '00:00';
    }
    let hourStr;
    let minuteStr;
    let secondsStr;
    var hour = Math.floor(seconds / 3600);
    seconds = seconds - hour * 3600;
    var minute = Math.floor(seconds / 60);
    seconds = seconds - minute * 60;
    if (hour < 10) {
      hourStr = "0" + hour;
    } else {
      hourStr = "" + hour;
    }
    if (minute < 10) {
      minuteStr = "0" + minute;
    } else {
      minuteStr = "" + minute;
    }
    if (seconds < 10) {
      secondsStr = "0" + seconds;
    } else {
      secondsStr = "" + seconds;
    }
    if (isHideHour && hourStr == '00') {
      return minuteStr + ':' + secondsStr;
    }
    return hourStr + ':' + minuteStr + ':' + secondsStr;
  }
  /**
   * 开始时间和结束时间比较大小
   * @param startTime 开始日期字符串
   * @param endTime 结束日期字符串
   */
  static compareDate(startTime, endTime) {
    let tempStart = Date.parse(startTime);
    let tempEnd = Date.parse(endTime);
    return tempStart > tempEnd;
  }

  static compareGTDate(startTime, endTime) {
    let tempStart = Date.parse(startTime);
    let tempEnd = Date.parse(endTime);
    return tempStart > tempEnd;
  }

  /**
   * 判断输入的是否是金额的数据
   */
  static isPrice(obj: any): boolean {
    var objRegExp = /^[0-9]+(.[0-9]{1,2})?$/;
    return objRegExp.test(obj);
  }
  /**
   * 只能够输入金额数字
   * @param value  输入的源数据
   * @param notMinus  true输入非负数，false输出负数
   * @param isInt  是否整数
   */
  static moneyFormat(value: string, notMinus: boolean, isInt?: boolean): string {
    // 先把非数字的都替换掉，除了数字负号和点
    value = !!notMinus ? value.replace(/[^\d.]/g, '') : value.replace(/[^-\d.]/g, '');
    // 必须保证第一个不是.
    value = value.replace(/^\./g, '');
    // 保证只有出现一个.而没有多个.
    value = value.replace(/\.{2,}/g, '.');
    // 保证.只出现一次，而不能出现两次以上
    value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
    // 只能两位小数点
    if (isInt) {
      value = value.substring(0, value.indexOf('.') === -1 ? value.length : (value.indexOf('.')));
    } else {
      value = value.substring(0, value.indexOf('.') === -1 ? value.length : (value.indexOf('.') + 3));
    }
    return value;
  }



  //http中的get访问的一个参数的拼接
  static Urlsplice(baseParam: any, url: string): string {
    let paramsArray = [];
    Object.keys(baseParam).forEach(key => paramsArray.push(key + '=' + baseParam[key]));
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&');
    } else {
      url += '&' + paramsArray.join('&');
    }
    return url;
  }

  //网络数据请求失败的一个处理封装
  static newError(res) {
    if (res.status === -1 || res.status === 0) {
      return '网络异常，请稍后再试';
    } else if (res.status === 401) {
      return '暂停访问';
    } else if (res.status === 404) {
      return '资源未找到';
    } else if (res.status === 502) {
      return '网络异常';
    } else if (res.status === 503) {
      return '连接数过多，请稍后...';
    } else {
      if (res._body != null && /\w+[\s\.]\w+/.test(res._body)) {
        return '系统异常';
      }
    }
  }
  /**
   * 获取目标一维数组，几个元素组合
   * @param targetArr 目标一维数组
   * @param isAll true是全组合，false结合selectNum的参数使用
   * @param selectNum 选择几个元素组合,isAll为false才有用
   */
  static arrayCombine(targetArr, isAll, selectNum) {
    if (!targetArr || !targetArr.length) {
      return [];
    }
    var len = targetArr.length;
    var resultArrs = [];
    for (var n = 1; n < len; n++) {
      var flagArrs = this.getFlagArrs(len, n);
      while (flagArrs.length) {
        var flagArr = flagArrs.shift();
        var combArr = [];
        for (var i = 0; i < len; i++) {
          flagArr[i] && combArr.push(targetArr[i]);
        }
        if (isAll) { // 所有组合
          resultArrs.push(combArr);
        } else {
          if (combArr.length == selectNum) {
            resultArrs.push(combArr.join(','));
          }
        }
      }
    }
    return resultArrs;
  }
  /**
   * 获得从m中取n的所有组合做为一个中间获取组合的的数据
   */
  static getFlagArrs(m, n) {
    if (!n || n < 1) {
      return [];
    }
    var resultArrs = [],
      flagArr = [],
      isEnd = false,
      i, j, leftCnt;
    for (i = 0; i < m; i++) {
      flagArr[i] = i < n ? 1 : 0;
    }
    resultArrs.push(flagArr.concat());
    while (!isEnd) {
      leftCnt = 0;
      for (i = 0; i < m - 1; i++) {
        if (flagArr[i] == 1 && flagArr[i + 1] == 0) {
          for (j = 0; j < i; j++) {
            flagArr[j] = j < leftCnt ? 1 : 0;
          }
          flagArr[i] = 0;
          flagArr[i + 1] = 1;
          var aTmp = flagArr.concat();
          resultArrs.push(aTmp);
          if (aTmp.slice(-n).join("").indexOf('0') == -1) {
            isEnd = true;
          }
          break;
        }
        flagArr[i] == 1 && leftCnt++;
      }
    }
    return resultArrs;
  }

  /**
   * 数组和数组的组合
   * @param arr   [[1,2],[3,4]]  组合后1,3|1,4|2,3|2,4
   */
  static doExchange(arr) {
    var len = arr.length;
    // 当数组大于等于2个的时候
    if (len >= 2) {
      // 第一个数组的长度
      var len1 = arr[0].length;
      // 第二个数组的长度
      var len2 = arr[1].length;
      // 2个数组产生的组合数
      var lenBoth = len1 * len2;
      //  申明一个新数组
      var items = new Array(lenBoth);
      // 申明新数组的索引
      var index = 0;
      for (var i = 0; i < len1; i++) {
        for (var j = 0; j < len2; j++) {
          if (arr[0][i] instanceof Array) {
            items[index] = arr[0][i].concat(arr[1][j]);
          } else {
            items[index] = [arr[0][i]].concat(arr[1][j]);
          }
          index++;
        }
      }
      var newArr = new Array(len - 1);
      for (var i = 2; i < arr.length; i++) {
        newArr[i - 1] = arr[i];
      }
      newArr[0] = items;
      return this.doExchange(newArr);
    } else {
      return arr[0];
    }
  }

  /**
   * 获取UUID
   * @param len 
   * @param radix 
   */

  static UUID(len?: number, radix?: number) {
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) {//Compact form 
        uuid[i] = chars[0 | Math.random() * radix];
      }
    } else {
      // rfc4122, version 4 form  
      var r;
      // rfc4122 requires these characters  
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      // Fill in random data.  At i==19 set the high bits of clock sequence as  
      // per rfc4122, sec. 4.1.5  
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }

  /**
   * 获取资源的路径
   * @param filePath 文件的路径
   */
  static isAssetTypeAnImage(filePath: string) {
    let ext = filePath.substr(filePath.lastIndexOf(".") + 1)
    // 'webp', 'psd', 'svg', 'tiff'
    return ['png', 'jpg', 'jpeg', 'bmp', 'gif'].indexOf(ext.toLowerCase()) !== -1;
  }

  static getBankNameByCode(code){
      let tempCode=code.toLocaleUpperCase(); 
      let codeList=[{code:"ICBC",name:"中国工商银行"},{code:"ABC",name:"中国农业银行"},{code:"CCB",name:"中国建设银行"},{code:"BCM",name:"交通银行"},{code:"CMBC",name:"民生银行"},{code:"CIB",name:"兴业银行"},{code: "SPDB", name: "浦发银行"},{code: "CNCB", name: "中信银行"},{code: "CEB", name: "光大银行"},{code: "CMB", name: "招商银行"},{code: "CGB", name: "广发银行"}, {code: "BOC", name: "中国银行"},{code: "HXB", name: "华夏银行"},{code: "PAB", name: "平安银行"},{code: "PSBC", name: "中国邮政"},{code: "BCCB", name: "北京银行"},{code: "SHB", name: "上海银行"},{code: "HRBB", name: "哈尔滨银行"},{code: "CZB", name: "浙商银行"},{code: "CSCB", name: "长沙银行"},{code: "QDCCB", name: "青岛银行"},{code: "ALIPAY", name: "支付宝"},{code: "WebMM", name: "微信支付"},{code: "QQPAY", name: "QQ钱包"},{code: "JDPAY", name: "京东钱包"},{code: "UNIPAY", name: "银联钱包/云闪付"},{code: "MEITUAN", name: "美团支付"},{code: "WXTM", name: "微信条码"},{code: "GDB", name: "广东发展银行"},{code: "ADBC", name: "农业发展银行"},{code: "RCC", name: "农村信用社"},{code: "CB", name: "商业银行"}]
      for(let i=0;i<codeList.length;i++){
          if(codeList[i].code==tempCode){
              return codeList[i].name;
              break;
          }
      }
      return "";
  }

  static getBankCodeUpper(code){
    let tempCode=code.toLocaleUpperCase(); 
    return tempCode;
}

  /**
   * 参数的AES对称加密
   * @param data 参数的数据，未加密的
   */
  static paramAESEncrypt(data){
    return CryptoJS.AES.encrypt(data,"com.wanluhui.www").toString();
  }
  /**
   * 
   * @param data  aes机密后的数据
   */
  static paramAESDecrypt(data){
    return CryptoJS.AES.decrypt(data,"com.wanluhui.www").toString(CryptoJS.enc.Utf8)
  }


  /**
   * 将url后面的参数反向序列为对象
   * @param strUrl  格式:  incode=255374&f=123
   */
  static urlToObj(strUrl){
    let string = strUrl.split('&');
		let res = {};
		for(let i = 0;i<string.length;i++){
			let str = string[i].split('=');
			if(str[0]!=''){
				res[str[0]]=str[1];
			}
		}
		return res;
  }






}
